<?php

namespace App\Supports\Payment\Methods\Goldcoin;

use App\Events\OrderRefundedEvent;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodRefund;

class RefundOrder extends Method implements MethodRefund
{
	public function validate($refund = null)
	{
		if (! $refund->order->isPaid()) {
			abort(403, '目标订单未支付');
		}
		if ($refund->order->isClosed()) {
			abort(403, '目标订单已关闭');
		}
		if ($refund->order->isCancelled()) {
			abort(403, '目标订单已取消');
		}
		if ($refund->order->has_refund) {
			abort(403, '目标订单已退款');
		}
		if ($refund->order->paid_method !== 'goldcoin') {
			abort(403, '目标订单不能通过金店账户退款');
		}
		if ($refund->refund_status !== 'confirmed') {
			abort(403, '目标售后未审核');
		}
		if ($refund->refund_status !== 'confirmed') {
			abort(403, '目标售后未审核');
		}
	}

	public function info($refund = null) {}

	public function refund($refund = null)
	{
		$this->validate($refund);

		DB::transaction(function () use ($refund) {

			$refund->update(['refund_status' => 'succeeded']);

			$order = $refund->order;
			$orderData['has_refund'] = true;

			if ($refund->is_order_cancel) {
				$orderData['cancelled_at'] = Carbon::now();
			}

			$order->update($orderData);

            $coins = $refund->refund_money;
            $data = ['order_refund_id' => $refund->id];
			account_coins($refund->user)->plusOrderRefund($coins, $data);
			event(new OrderRefundedEvent($refund));
		});
	}
}
